use actix_web::{web, HttpResponse, Responder};
use serde::Deserialize;
use serde_json::json;
use serde_with::NoneAsEmptyString;

pub fn set_routes(cfg: &mut web::ServiceConfig) {
    cfg.route("/", web::get().to(index))
        .route("/list", web::get().to(list))
        .route("/add", web::post().to(add));
}

async fn index() -> impl Responder {
    HttpResponse::Ok().body("user_controller")
}

#[serde_with::serde_as]
#[derive(Debug, Deserialize)]
struct Pagination {
    #[serde(rename(serialize = "pageSize", deserialize = "pageSize"))]
    #[serde_as(as = "NoneAsEmptyString")]
    #[serde(default)]
    page_size: Option<usize>,
}

async fn list(param: web::Query<Pagination>) -> impl Responder {
    super::shared::get_data_response(json!({
      "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678",
        ],
        "pageSize": param.page_size,
    }))
}

#[serde_with::serde_as]
#[derive(Debug, Deserialize)]
struct User {
    #[serde_as(as = "NoneAsEmptyString")]
    #[serde(default)]
    username: Option<String>,
}

async fn add(param: web::Json<User>) -> impl Responder {
    HttpResponse::Created().json(json!({
        "username": param.username,
    }))
}
